use model_graph_types::{
    connector::{Connector, ExecuteOptions, QueryOptions},
    database::{DataSource, DatabaseType},
    modeling::Value,
    transform::{DataTransformOptions, DataTransformStructUnit, DataTransformUnit},
};

use sqlite_connector::SqliteConnector;

/// 根据数据库获取到元数据
pub async fn transform(
    source: &DataSource,
    target: &DataSource,
    unit: &DataTransformStructUnit,
    options: &DataTransformOptions,
) -> anyhow::Result<()> {
    //连接数据库
    let source_connector = SqliteConnector::open(&source).await?;
    let target_connector = SqliteConnector::open(&target).await?;

    let tables = &unit.tables;
    let ignore = options.ignore_errs;

    let query_sql = String::from(
        "select name, type, tbl_name, rootpage, sql from sqlite_master where tbl_name = $1",
    );

    for table in tables {
        //
        let (_, result_values) = source_connector
            .query(
                &query_sql,
                &vec![Value::String(table.clone())],
                QueryOptions {},
            )
            .await?;
        tracing::debug!("result:{:?}", result_values);
        for value in result_values {
            match value {
                Value::Array(cols) => {
                    if let Some(Value::String(sql)) = cols.get(4) {
                        //
                        let result = target_connector
                            .execute(sql, &vec![], ExecuteOptions::default())
                            .await;
                        if !ignore {
                            if let Err(err) = result {
                                tracing::error!("{}:{} ", sql, err);
                                return Err(err);
                            }
                        }
                    }
                }
                _ => {
                    tracing::debug!("==");
                }
            }
        }
    }
    Ok(())
}
